#!/bin/env python
# -*- coding:utf-8
"""
@author:xingz
@file:Tictactoe.py
@time:2021/11/16
"""
from __future__ import annotations
from board import Board, Piece, Move
from typing import List
from enum import Enum


class TTTPiece(Piece, Enum):
    """
    0|1|2
    3|4|5
    6|7|8
    """
    X = "X"
    O = "O"
    E =  "   "  # stand-in for empty

    @property
    def opposite(self) -> TTTPiece:
        if self == TTTPiece.X:
            return TTTPiece.O
        elif self == TTTPiece.O:
            return TTTPiece.X
        else:
            return TTTPiece.E

    def __str__(self):
        return self.value


class TTTBoard(Board):
    def __init__(self, position=None, turn: TTTPiece = TTTPiece.X):
        if position is None:
            self.position: List[TTTPiece] = [TTTPiece.E] * 9
        else:
            self.position = position
        self._turn = turn

    @property
    def turn(self) -> Piece:
        return self._turn

    def move(self, location: Move) -> Board:
        temp_position: List[TTTPiece] = self.position.copy()
        temp_position[location] = self._turn
        return TTTBoard(temp_position, self._turn.opposite)

    @property
    def legal_moves(self) -> List[Move]:
        legal_moves: List[Move] = [Move(i) for i in range(len(self.position)) if self.position[i] == TTTPiece.E]
        return legal_moves

    @property
    def is_win(self) -> bool:
        combinations = [[0, 1, 2],
                        [3, 4, 5],
                        [6, 7, 8],
                        [0, 3, 6],
                        [1, 4, 7],
                        [2, 5, 8],
                        [0, 4, 8],
                        [2, 4, 6]]
        for comb in combinations:
            if self.position[comb[0]] == self.position[comb[1]] and self.position[comb[0]] == self.position[comb[2]] and self.position[comb[0]] != TTTPiece.E:
                return True
        return False

    def evaluate(self, player: Piece) -> float:
        """若当前局势已经赢，代表赢家为上一个player"""
        if self.is_win and self.turn == player:
            return -1
        elif self.is_win and self.turn != player:
            return 1
        else:
            return 0

    def __repr__(self):
        return f"""
        {self.position[0]}|{self.position[1]}|{self.position[2]}
        {self.position[3]}|{self.position[4]}|{self.position[5]}
        {self.position[6]}|{self.position[7]}|{self.position[8]}
        """
